﻿using Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ProdService;
using ViewModels.JsonResult;
using ViewModels.User;

namespace UI.ApiControllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : BaseController
    {
        private ContactService contactService;
        public UserController(PhoneService phoneService, UserService userService, ContactService contactService)
            : base(userService, phoneService)
        {
            this.contactService = contactService;
        }

        [HttpGet]
        [Route(nameof(HasPhone))]
        public bool HasPhone(string number)
        {
            return false;
        }

        [HttpGet]
        [Route(nameof(CheckInvitedBy))]
        public bool CheckInvitedBy(string inviteCode)
        {
            return userService.CheckInvited(inviteCode);
        }

        [HttpGet]
        [Route(nameof(NameIsAavailable))]
        public bool NameIsAavailable(string logonName)
        {
            return !userService.NameHasUsed(logonName);
        }

        [HttpPost]
        [Route(nameof(Register))]
        public RegisterResult Register([FromForm] RegisterModel model, bool remember)
        {
            RegisterResult result = new();

            if (!string.IsNullOrEmpty(model.LogonName) &&
                userService.GetByName(model.LogonName) != null)
            {
                result.Errors.Add(nameof(model.LogonName), "* 用户名重复，请重新输入");
            }//else continue
            if (!userService.CheckInvited(model.InviteCode))
            {
                result.Errors.Add(nameof(model.InviteCode), "* 邀请码错误");
            }//else continue
            if (!string.IsNullOrEmpty(phoneService.CheckToken(model.Number, model.CheckCode)))
            {
                result.Errors.Add(nameof(model.CheckCode), "* 短信验证码错误");
            }//else continue
            if (result.Errors.Count() == 0)
            {
                int userId = userService.Register(model);
                userService.On(userId, remember);
            }
            result.Succeed = result.Errors.Count() == 0;
            return result;
        }

        [HttpPost]
        [Route(nameof(ChangeNames))]
        public void ChangeNames([FromForm] NameModel model)
        {
            userService.ChangeNames(model);
        }

    }
}
